<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/5/4
 * Time: 20:47
 */

namespace app\storage\service\bom;

use app\storage\model\ReelsModel;
use service\excel\ExcelWrite;

class RetentionBomService extends BaseBomService
{

    public function findReels($param)
    {
        $subMaterielId = $param['subMaterielId'];
        $day = $param['day'];
        $range = $param['range'];
        $condition = trim($param['condition']);
        $storageUuid = $param['storageUuid'];
        $day = date("Y-m-d", strtotime("-$day day"));
        $day = $condition == 'like' ? $day . '%' : $day;

        if (empty($subMaterielId)){
            $subMaterielId = "";
        }
        $rangeWhere = ["", "container_code is null or container_code = ''", "container_code is not null and container_code != ''"];
        $whereString = $rangeWhere[$range];
        $where = [
            'status' => 1,
            'time' => ["$condition", $day],
            'storage_uuid' => $storageUuid,
        ];
        $subMaterielId = '%'.$subMaterielId.'%';
        $reelsModel = new ReelsModel();
        $result = $reelsModel->field('sub_materiel_id,reel_id,count,seat_code,container_code,time,DATEDIFF(now(),time) as day')
            ->order('seat_code asc,container_code asc')
            ->where($where)
            ->where('sub_materiel_id','like',$subMaterielId)
            ->where($whereString)
            ->select();
        return ret_template(true, '查询成功', $result);
    }


    public function downloadExcel(array $reels,$storageUuid = '')
    {
        if (empty($reels)) {
            return ret_template(false, '没有勾选条码');
        }

        $where['status'] = 1;
        $where['reel_id'] = array('in', $reels);
        //到站位上查找数据
        $reelsModel = new ReelsModel();
        $result = $reelsModel->field("sub_materiel_id,sum(count) as count")
            ->group('sub_materiel_id')
            ->where($where)->select()
            ->toArray();
        $init = ['sub_materiel_id'=>'料号','count'=>'数量'];
        $result = ExcelWrite::excelExport('滞留出库',$init,$result,true);
        return $result;
    }
}